package com.hissy.common;

import java.io.IOException;
import java.util.Map;

import com.hissy.entity.emp.MenuVo;
import com.hissy.service.EmpService;
import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by zhangyanfei on 2018/9/12.
 * 自定义菜单标签
 *
 * @author zhangyanfei
 * @date 2018/09/12
 */
public class MenuDirective implements TemplateDirectiveModel {
    private static final String VARIABLE_MENU = "_menuMap";

    @Autowired
    private EmpService empService;

    /**
     * @param environment           同一个ftl共有
     * @param params                 标签参数
     * @param templateModels
     * @param templateDirectiveBody
     * @throws TemplateException
     * @throws IOException <@menu empId=Session.userSessionKey.id;children>
     *
     * env.setCustomAttribute(MenuDirective.VARIABLE_MENU, menu);
     * loopVars[0] = ObjectWrapper.BEANS_WRAPPER.wrap(menu.getChildren());
     * body.render(env.getOut());
     */
    @Override
    public void execute(Environment environment, Map params, TemplateModel[] templateModels,
                        TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        Long empId = params.get("empId") == null ? null : Long.parseLong(params.get("empId").toString());
        MenuVo menu = (MenuVo)environment.getCustomAttribute(MenuDirective.VARIABLE_MENU);
        if (menu == null) {
            menu = empService.getMenusByEmpId(empId);
            environment.setCustomAttribute(VARIABLE_MENU, menu);
            templateModels[0] = ObjectWrapper.BEANS_WRAPPER.wrap(menu.getChildren());
            templateDirectiveBody.render(environment.getOut());
        }
    }
}
